package net.yxsoft.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import net.yxsoft.service.common.BaseService;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import rapid.core.Authuser;
import rapid.core.TResult;

public class WarnService extends BaseService {
    public static final WarnService INSTANCE=new WarnService();

    /**
     * page
     * limit
     * loginUser  登入用户账号信息
     * */
    public JSONObject getWarnings(String page , String limit, Authuser loginUser)  {
        JSONObject jsonObject = new JSONObject();
        try{
            Record record = Db.findFirst("SELECT * FROM fn_form_data \n" +
                    "WHERE attrib_01=(SELECT id FROM fn_form WHERE code ='yyfwdygl')\n" +
                    "and attrib_37= ? ", loginUser.get("GROUP_NAMES").toString());
            if(record==null){
                jsonObject.put("error","无此应用单元服务");
                return jsonObject;
            }
            String baseUrl = record.getStr("attrib_35");//接口标识符(服务的登入url)
            String serviceParam = record.getStr("ATTRIB_36");//登入信息json
            JsonNode loginJsonNode = mocExecPost(baseUrl, serviceParam, null); //调用登入接口获得登入认证token
            String token = loginJsonNode.get("data").get("token").asText();
            String getWarnUrl = baseUrl.replace("/user/login", "/task/getWarnings");//修改成预警接口
            //调用应用单元远程接口创建应用单元账号
            JSONObject param = new JSONObject();
            param.put("page",page);
            param.put("limit",limit);
            JsonNode jsonNode = mocExecPost(getWarnUrl, param.toString(), token);
            JSONObject returnJson = JSONObject.parseObject(jsonNode.toString());// 将字符串解析为JSONObject
            return returnJson;
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("error",e.toString());
            return jsonObject;
        }
    }

    /**
     * 服务调用 执行Post请求
     *  url 请求地址
     *  param 请求参数
     *  jwtoken 认证信息
     * */
    public JsonNode mocExecPost(String url, String param, String jwtoken) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setConnectTimeout(5000) //连接超时时间
                        .setSocketTimeout(5000) //读取超时时间
                        .setConnectionRequestTimeout(5000) //请求超时时间
                        .build())
                .build();
        CloseableHttpResponse response = null;
        JsonNode jsonNode =null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("accept"," application/json");
            //认证不为空，则加上认证信息
            if(StringUtils.isNotBlank(jwtoken)){
                httpPost.setHeader("jwtoken",jwtoken);
            }
            // 创建参数列表
            if (param != null) {
                StringEntity postingString = new StringEntity(param, ContentType.APPLICATION_JSON);
                httpPost.setEntity(postingString);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            // 将字符串转换为JSON对象
            ObjectMapper objectMapper = new ObjectMapper();
            jsonNode = objectMapper.readValue(resultString, JsonNode.class);
            response.close();
        } catch (Exception e) {
            throw e;
        }
        return jsonNode;
    }

}
